/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.FrameControlBaoCao;

import TOOL.Ulti;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

/**
 *
 * @author 10520_000
 */
public class JIFBaoCaoTon extends javax.swing.JInternalFrame {
    private String message ="";
    private String thang_HienTai, nam_HienTai, maBCTruoc_HienTai;
    /**
     * Creates new form JIFGroupKH
     */
    public JIFBaoCaoTon()
    {

            initComponents();
            
            this.setSize(1000, 620);
            
            jTableTon.addMouseListener(new MouseAdapter(){
                @Override
                public void mouseReleased(MouseEvent e){
                    if(e.isPopupTrigger()){
                        jPopupMenu1.show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            });
            Ulti.CleanTabe(jTableTon);
        
            
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItemAdd = new javax.swing.JMenuItem();
        jMenuItemDel = new javax.swing.JMenuItem();
        jMenuItemSua = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItemLoad = new javax.swing.JMenuItem();
        jMenuItemTim = new javax.swing.JMenuItem();
        jMenuItemPrint = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItemNhap = new javax.swing.JMenuItem();
        jMenuItemXuat = new javax.swing.JMenuItem();
        cb_Thang = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cb_Nam = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jLabelTieuDe = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        btn_Luu = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        btn_lapbaocaotudong = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        btn_xuatBCTuyChon = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        cb_TuThang = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cb_TuNam = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        cb_DenThang = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        cb_DenNam = new javax.swing.JComboBox();
        btn_XuatTatCaBaoCao = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableTon = new javax.swing.JTable();

        jMenuItemAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/add1.png"))); // NOI18N
        jMenuItemAdd.setText("Thêm mới");
        jPopupMenu1.add(jMenuItemAdd);

        jMenuItemDel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/del.png"))); // NOI18N
        jMenuItemDel.setText("Xóa");
        jPopupMenu1.add(jMenuItemDel);

        jMenuItemSua.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/sua.png"))); // NOI18N
        jMenuItemSua.setText("Sửa");
        jPopupMenu1.add(jMenuItemSua);
        jPopupMenu1.add(jSeparator1);

        jMenuItemLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/refresh.png"))); // NOI18N
        jMenuItemLoad.setText("Tải lại");
        jPopupMenu1.add(jMenuItemLoad);

        jMenuItemTim.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/search1.png"))); // NOI18N
        jMenuItemTim.setText("Tìm kiếm");
        jPopupMenu1.add(jMenuItemTim);

        jMenuItemPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/print.png"))); // NOI18N
        jMenuItemPrint.setText("In ấn");
        jPopupMenu1.add(jMenuItemPrint);
        jPopupMenu1.add(jSeparator2);

        jMenuItemNhap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/input.png"))); // NOI18N
        jMenuItemNhap.setText("Nhập từ Excel");
        jPopupMenu1.add(jMenuItemNhap);

        jMenuItemXuat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/excel.png"))); // NOI18N
        jMenuItemXuat.setText("Xuất ra Excel");
        jPopupMenu1.add(jMenuItemXuat);

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("BÁO CÁO TỒN KHO");
        setAutoscrolls(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
        });

        cb_Thang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
        cb_Thang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_ThangActionPerformed(evt);
            }
        });

        jLabel1.setText("Tháng:");

        jLabel2.setText("Năm:");

        cb_Nam.setEditable(true);
        cb_Nam.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2013" }));
        cb_Nam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_NamActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(49, 122, 233));
        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabelTieuDe.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabelTieuDe.setForeground(new java.awt.Color(255, 255, 255));
        jLabelTieuDe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/add.png"))); // NOI18N
        jLabelTieuDe.setText("Lập báo cáo tồn");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelTieuDe)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelTieuDe)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBackground(new java.awt.Color(51, 51, 51));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btn_Luu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/save.png"))); // NOI18N
        btn_Luu.setText("Lưu");
        btn_Luu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_LuuActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/close2.png"))); // NOI18N
        jButton4.setText("Thoát");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        btn_lapbaocaotudong.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/refresh.png"))); // NOI18N
        btn_lapbaocaotudong.setText("Lập Báo Cáo Tự Động");
        btn_lapbaocaotudong.setEnabled(false);
        btn_lapbaocaotudong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_lapbaocaotudongActionPerformed(evt);
            }
        });

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/del.png"))); // NOI18N
        jButton6.setText("Xuất Báo Cáo Hiện Tại");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        btn_xuatBCTuyChon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/del.png"))); // NOI18N
        btn_xuatBCTuyChon.setText("Xuất Báo Cáo Tùy Chọn");
        btn_xuatBCTuyChon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_xuatBCTuyChonActionPerformed(evt);
            }
        });

        jLabel4.setText("Tháng:");

        cb_TuThang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
        cb_TuThang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_TuThangActionPerformed(evt);
            }
        });

        jLabel5.setText("Năm:");

        cb_TuNam.setEditable(true);
        cb_TuNam.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2012", "2013" }));
        cb_TuNam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_TuNamActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Từ");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel7.setText("Đến");

        jLabel8.setText("Tháng:");

        cb_DenThang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
        cb_DenThang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_DenThangActionPerformed(evt);
            }
        });

        jLabel9.setText("Năm:");

        cb_DenNam.setEditable(true);
        cb_DenNam.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2012", "2013" }));
        cb_DenNam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_DenNamActionPerformed(evt);
            }
        });

        btn_XuatTatCaBaoCao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/del.png"))); // NOI18N
        btn_XuatTatCaBaoCao.setText("Xuất Tất Cả Báo Cáo");
        btn_XuatTatCaBaoCao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_XuatTatCaBaoCaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                        .addComponent(btn_lapbaocaotudong, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(btn_XuatTatCaBaoCao, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(152, 152, 152)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(12, 12, 12)
                                .addComponent(jLabel4))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cb_TuThang, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cb_DenThang, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel9))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(jLabel5)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(cb_TuNam, 0, 1, Short.MAX_VALUE)
                            .addComponent(cb_DenNam, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btn_xuatBCTuyChon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 242, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_Luu, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton6)
                            .addComponent(btn_xuatBCTuyChon))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_lapbaocaotudong)
                        .addGap(7, 7, 7)
                        .addComponent(btn_XuatTatCaBaoCao))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(btn_Luu)
                            .addGap(36, 36, 36)
                            .addComponent(jButton4)
                            .addGap(3, 3, 3))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4)
                                .addComponent(cb_TuThang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(cb_TuNam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6))
                            .addGap(7, 7, 7)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel8)
                                .addComponent(cb_DenThang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(cb_DenNam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel9)
                                .addComponent(jLabel7)))))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jTableTon.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Mã sách", "Tên sách", "Tác Giả", "Tồn Đầu", "Phát Sinh", "Tồn Cuối"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableTon);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cb_Thang, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cb_Nam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cb_Thang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(cb_Nam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        // TODO add your handling code here:
        if(checkPreviousReport(this)){
            LoadData();
        } else
        {
             JOptionPane.showConfirmDialog(this,message,"Lỗi", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
              btn_lapbaocaotudong.setEnabled(true);
        }
    }//GEN-LAST:event_formAncestorAdded

    private void btn_lapbaocaotudongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_lapbaocaotudongActionPerformed
            TaoBaoCaoTuDong();
    }//GEN-LAST:event_btn_lapbaocaotudongActionPerformed

    private void btn_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_LuuActionPerformed
        // TODO add your handling code here:
        if((thang_HienTai == null || nam_HienTai == null) || maBCTruoc_HienTai ==null){
                  JOptionPane.showConfirmDialog(this, "Tất cả báo cáo đã được lưu!","Thông Báo",JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
            }
           else LuuDuLieu();
    }//GEN-LAST:event_btn_LuuActionPerformed

    private void cb_ThangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_ThangActionPerformed
        // TODO add your handling code here:
        if(checkPreviousReport(this)){
            LoadData();
        } else
        {
              TOOL.Ulti.CleanTabe(jTableTon);
             JOptionPane.showConfirmDialog(this,message,"Lỗi", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
              btn_lapbaocaotudong.setEnabled(true);
        }
    }//GEN-LAST:event_cb_ThangActionPerformed

    private void cb_NamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_NamActionPerformed
        // TODO add your handling code here:
        if(checkPreviousReport(this)){
           LoadData();
        } else
        {
              TOOL.Ulti.CleanTabe(jTableTon);
             JOptionPane.showConfirmDialog(this,message,"Lỗi", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
              btn_lapbaocaotudong.setEnabled(true);
        }
    }//GEN-LAST:event_cb_NamActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        LuuDuLieu();
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void btn_xuatBCTuyChonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_xuatBCTuyChonActionPerformed
        // TODO add your handling code here:
         ExportOptionReport();
    }//GEN-LAST:event_btn_xuatBCTuyChonActionPerformed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // TODO add your handling code here:
            LuuDuLieu();
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // TODO add your handling code here:
         String message = null;
        if(checkPreviousReport(this)){
            ExportCurrentReport();
        } else
        {
              TOOL.Ulti.CleanTabe(jTableTon);
             JOptionPane.showConfirmDialog(this,message,"Lỗi", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
             btn_lapbaocaotudong.setEnabled(true);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void cb_TuThangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_TuThangActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cb_TuThangActionPerformed

    private void cb_TuNamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_TuNamActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cb_TuNamActionPerformed

    private void cb_DenThangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_DenThangActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cb_DenThangActionPerformed

    private void cb_DenNamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_DenNamActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cb_DenNamActionPerformed

    private void btn_XuatTatCaBaoCaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_XuatTatCaBaoCaoActionPerformed
        // TODO add your handling code here:
        ExportAllReport();
    }//GEN-LAST:event_btn_XuatTatCaBaoCaoActionPerformed

    public void exportStudentMarkToPdf(int thangBC, int namBC, String maBC,String maBCTruoc,String ngayLapBC,String targetFolder,String extension,boolean showMessageBox){  
           Connection con = null;  
           try {  
                String source = "src/BaoCaoTon.jrxml";
               JasperReport jr = JasperCompileManager.compileReport(source);  
              // InputStream jr = this.getClass().getClassLoader().getResourceAsStream(source); 
                Map<String, Object> params = new HashMap<>();  
                params.put("ThangBC",thangBC );  
                params.put("NamBC", namBC); 
                 params.put("NgayLapBC", ngayLapBC); 
                 params.put("MaBC", maBC); 
                 params.put("MaBCTruoc",maBCTruoc);
                con = DAO.DAO.getConnection();
            
                JasperPrint jp = JasperFillManager.fillReport(jr, params, con);  
                if("Pdf file".equals(extension))
                        try (OutputStream os = new FileOutputStream(targetFolder+".pdf")) {
                           JasperExportManager.exportReportToPdfStream(jp, os);  
                           os.flush();
                            if(showMessageBox)
                                JOptionPane.showConfirmDialog(this,"Xuất file thành công!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
                       }  
                else if("Excel file".equals(extension))
                {
                     try (OutputStream os = new FileOutputStream(targetFolder+".xls")) {
                        JRXlsExporter exporterXLS = new JRXlsExporter();
                        exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jp);
                        exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, os);
                        exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
                        exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
                        exporterXLS.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE);
                        exporterXLS.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
                        exporterXLS.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
                        exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
                        exporterXLS.exportReport();
                         os.flush();
                         if(showMessageBox)
                         JOptionPane.showConfirmDialog(this,"Xuất file thành công!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
                       }  
                }
                else if("HTML file".equals(extension)){
                    JasperExportManager.exportReportToHtmlFile(jp,targetFolder+".html");
                     if(showMessageBox)
                    JOptionPane.showConfirmDialog(this,"Xuất file thành công!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
                } else{
                      try (OutputStream os = new FileOutputStream(targetFolder+".pdf")) {
                           JasperExportManager.exportReportToPdfStream(jp, os);  
                           os.flush();
                            if(showMessageBox)
                           JOptionPane.showConfirmDialog(this,"Xuất file thành công!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
                       }  
                }
           } catch (JRException | IOException e) {  
                e.printStackTrace();  
                 if(showMessageBox)
                JOptionPane.showConfirmDialog(this,"Xuất file thất bại!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
           }finally{  
                try{  
                     if(con != null && !con.isClosed()){  
                          //con.close();  
                     }  
                }catch(Exception e){  
                     e.printStackTrace();  
                }  
           }  
      
 }  
public void LoadData(){
     try {
            // TODO add your handling code here:
            TOOL.Ulti.CleanTabe(jTableTon);
            int thang = Integer.parseInt(cb_Thang.getSelectedItem().toString());
            int nam  =Integer.parseInt(cb_Nam.getSelectedItem().toString());
             String maBCChon = LayMaBCTTheoThangNam(thang, nam);
           
           String  maBCTruoc;
            if(maBCChon !=null) maBCTruoc = getPreviousId(maBCChon);
            else {
             maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
             thang_HienTai = String.valueOf(thang);
             nam_HienTai = String.valueOf(nam);
             maBCTruoc_HienTai = maBCTruoc;
         }
            
            
            ResultSet  res = new BUS.BaoCaoTon().ThongKeTon(thang, nam,maBCTruoc);
            int count =1;
            while(res.next()){
                ((DefaultTableModel)((JTable)jTableTon).getModel()).addRow(new Object[]
                    {
                        count++, res.getString(2),res.getString(3), res.getString(4),res.getString(5), res.getString(6),res.getString(7)

                    });            }
                 JOptionPane.showConfirmDialog(this, "Load dữ liệu thành công!","Thông báo",JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
             
                } catch (SQLException ex) {
                    Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
                }
              
}
 public void ExportCurrentReport(){
            int thang = Integer.parseInt(cb_Thang.getSelectedItem().toString());
            int nam  =Integer.parseInt(cb_Nam.getSelectedItem().toString());
            JFileChooser j = new JFileChooser();
            j.setFileSelectionMode(JFileChooser.FILES_ONLY);
            j.addChoosableFileFilter(new FileNameExtensionFilter("Pdf file", "pdf"));
            j.addChoosableFileFilter(new FileNameExtensionFilter("Excel file", "xls"));
            j.addChoosableFileFilter(new FileNameExtensionFilter("HTML file", "html"));

            Integer opt = j.showSaveDialog(this);
            File selectedFile;
            String extension =null;
        switch (j.getFileFilter().getDescription()) {
            case "Excel file":
                selectedFile = new File(j.getSelectedFile().getPath()+".xls");
                extension = ".xls";
                break;
            case "HTML file":
                selectedFile = new File(j.getSelectedFile().getPath()+".html");
                 extension = ".html";
                break;
            default:
                selectedFile = new File(j.getSelectedFile().getPath()+".pdf");
                 extension = ".pdf";
                break;
        }
            if ((selectedFile != null) && selectedFile.exists() ){
                int response = JOptionPane.showConfirmDialog(this,
                    "Tập tin " +selectedFile.getName()+
                    "  đã tồn tại. Bạn có muốn ghi đè?",
                    "Tập tin đã tồn tại", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
                if (response != JOptionPane.YES_OPTION)
                return;
            }
            Date todayD=new Date(System.currentTimeMillis()); 

//Khai bao dinh dang ngay thang
            SimpleDateFormat dayFormat= new SimpleDateFormat("dd/MM/yyyy"); 

//parse ngay thang sang dinh dang va chuyen thanh string.
             String todayS=dayFormat.format(todayD.getTime()); 
              ResultSet resMaBC = new BUS.BaoCaoTon().LayMaBCTTheoThangNam(thang, nam);
             String maBCChon = null;
        try {
            while(resMaBC.next()){
                     maBCChon = resMaBC.getString(1);
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
             JOptionPane.showConfirmDialog(this,"Không thể xuất báo cáo vì dữ liệu báo cáo tháng "+thang+" năm "+nam+" chưa được lưu!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
        }
        if(maBCChon!=null)
        exportStudentMarkToPdf(thang,nam, maBCChon,getPreviousId(maBCChon),todayS,j.getSelectedFile().getPath(),  j.getFileFilter().getDescription(),true);
       else
             JOptionPane.showConfirmDialog(this,"Không thể xuất báo cáo vì dữ liệu báo cáo tháng "+thang+" năm "+nam+" chưa được lưu!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
      
 }
 
 public void ExportAllReport(){
            JFileChooser j = new JFileChooser();
            j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            j.addChoosableFileFilter(new FileNameExtensionFilter("Pdf file", "pdf"));
            j.addChoosableFileFilter(new FileNameExtensionFilter("Excel file", "xls"));
            j.addChoosableFileFilter(new FileNameExtensionFilter("HTML file", "html"));

            Integer opt = j.showSaveDialog(this);
            File selectedFile;
            String extension =null;
        switch (j.getFileFilter().getDescription()) {
            case "Excel file":
                selectedFile = new File(j.getSelectedFile().getPath()+".xls");
                extension = ".xls";
                break;
            case "HTML file":
                selectedFile = new File(j.getSelectedFile().getPath()+".html");
                 extension = ".html";
                break;
            default:
                selectedFile = new File(j.getSelectedFile().getPath()+".pdf");
                 extension = ".pdf";
                break;
        }
            if ((selectedFile != null) && selectedFile.exists() ){
                int response = JOptionPane.showConfirmDialog(this,
                    "Tập tin " +selectedFile.getName()+
                    "  đã tồn tại. Bạn có muốn ghi đè?",
                    "Tập tin đã tồn tại", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
                if (response != JOptionPane.YES_OPTION)
                return;
            }
             String maBCTruoc = "BCT001";
     ResultSet res = new BUS.BaoCaoTon().LayThangBCT("BCT001");
     int thangDauTien = 0,namDauTien = 0;
        try {
            while(res.next()){
                thangDauTien = Integer.parseInt(res.getString(1));
                namDauTien = Integer.parseInt(res.getString(2));
            }
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
        
     ResultSet res2 = new BUS.BaoCaoTon().LayThangBCT(getPreviousId(new BUS.BaoCaoTon().GenerateID()));
     int thangCuoi = 0,namCuoi= 0;
        try {
            while(res2.next()){
                thangCuoi = Integer.parseInt(res2.getString(1));
                namCuoi = Integer.parseInt(res2.getString(2));
            }
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        ExportMultiReport(thangDauTien,namDauTien,thangCuoi,namCuoi,maBCTruoc,j.getSelectedFile().getPath(),j.getFileFilter().getDescription());
 }
 
 public void ExportOptionReport(){
        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        j.addChoosableFileFilter(new FileNameExtensionFilter("Pdf file", "pdf"));
        j.addChoosableFileFilter(new FileNameExtensionFilter("Excel file", "xls"));
        j.addChoosableFileFilter(new FileNameExtensionFilter("HTML file", "html"));
         int thangDauTien = Integer.parseInt(cb_TuThang.getSelectedItem().toString());
         int namDauTien = Integer.parseInt(cb_TuNam.getSelectedItem().toString());
         int thangCuoi = Integer.parseInt(cb_DenThang.getSelectedItem().toString());
         int namCuoi = Integer.parseInt(cb_DenNam.getSelectedItem().toString());
         ResultSet res = new BUS.BaoCaoTon().LayThangBCT("BCT001");
     int thangBCDau = 0,namBCDau = 0;
        try {
            while(res.next()){
                thangBCDau = Integer.parseInt(res.getString(1));
                namBCDau = Integer.parseInt(res.getString(2));}
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
        ResultSet res2 = new BUS.BaoCaoTon().LayThangBCT(getPreviousId(new BUS.BaoCaoTon().GenerateID()));
     int thangBCCuoi= 0,namBCCuoi = 0;
        try {
            while(res2.next()){
                thangBCCuoi = Integer.parseInt(res2.getString(1));
                namBCCuoi = Integer.parseInt(res2.getString(2));}
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
         if (checkValidExportOption(thangDauTien, namDauTien, thangCuoi, namCuoi,thangBCDau,namBCDau,thangBCCuoi,namBCCuoi)){
                Integer opt = j.showSaveDialog(this);
           File selectedFile;
           String extension =null;
        switch (j.getFileFilter().getDescription()) {
            case "Excel file":
                selectedFile = new File(j.getSelectedFile().getPath()+".xls");
                extension = ".xls";
                break;
            case "HTML file":
                selectedFile = new File(j.getSelectedFile().getPath()+".html");
                 extension = ".html";
                break;
            default:
                selectedFile = new File(j.getSelectedFile().getPath()+".pdf");
                 extension = ".pdf";
                break;
        }
            if ((selectedFile != null) && selectedFile.exists() ){
                int response = JOptionPane.showConfirmDialog(this,
                    "Tập tin " +selectedFile.getName()+
                    "  đã tồn tại. Bạn có muốn ghi đè?",
                    "Tập tin đã tồn tại", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
                if (response != JOptionPane.YES_OPTION)
                return;
            }
             if(checkDateLargerDate(thangBCDau,namBCDau,thangDauTien,namDauTien) && !checkDateLargerDate(thangBCCuoi,namBCCuoi,thangCuoi,namCuoi))
                 ExportMultiReport(thangBCDau,namBCDau,thangBCCuoi,namBCCuoi,  LayMaBCTTheoThangNam(thangBCDau,namBCDau),j.getSelectedFile().getPath(),j.getFileFilter().getDescription());
            else  if(!checkDateLargerDate(thangBCDau,namBCDau,thangDauTien,namDauTien) && checkDateLargerDate(thangBCCuoi,namBCCuoi,thangCuoi,namCuoi))
                 ExportMultiReport(thangDauTien,namDauTien,thangCuoi,namCuoi,  LayMaBCTTheoThangNam(thangDauTien,namDauTien),j.getSelectedFile().getPath(),j.getFileFilter().getDescription());
             else  if(!checkDateLargerDate(thangBCCuoi,namBCCuoi,thangCuoi,namCuoi) &&!checkDateLargerDate(thangBCDau,namBCDau,thangDauTien,namDauTien))
                 ExportMultiReport(thangDauTien,namDauTien,thangBCCuoi,namBCCuoi,  LayMaBCTTheoThangNam(thangDauTien,namDauTien),j.getSelectedFile().getPath(),j.getFileFilter().getDescription());
            else  if(checkDateLargerDate(thangBCDau,namBCDau,thangDauTien,namDauTien) && checkDateLargerDate(thangBCCuoi,namBCCuoi,thangCuoi,namCuoi))
                 ExportMultiReport(thangBCDau,namBCDau,thangCuoi,namCuoi,  LayMaBCTTheoThangNam(thangBCDau,namBCDau),j.getSelectedFile().getPath(),j.getFileFilter().getDescription());
        
         }
         else
              JOptionPane.showConfirmDialog(this,"Không có báo cáo nào được xuất. Vui lòng kiểm tra lại ngày tháng!!","Thông Báo", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
 }
 public boolean checkDateLargerDate(int thangDau, int namDau, int thangCuoi, int namCuoi){
     if(namDau == namCuoi){
        if( thangDau >=thangCuoi)
            return true;
     }
     if(namDau > namCuoi)
            return true;
     return  false;
 }
 public boolean checkValidExportOption(int thangDauTien, int namDauTien, int thangCuoi, int namCuoi,int thangBCDau,int namBCDau,int thangBCCuoi, int namBCCuoi){
     if(namDauTien>namCuoi)
         return false;
     if(namDauTien ==namCuoi)
         if(thangDauTien>thangCuoi)
             return false;
      
           if(namBCCuoi<namDauTien)
               return false;
           if(namBCDau>namCuoi)
               return false;
           if(namBCCuoi == namDauTien)
           {
               if(thangBCCuoi<thangDauTien)
                   return false;
           }
           if(namBCDau == namCuoi){
                if(thangBCDau>thangCuoi)
                   return false;
           }
     return true;
 }
 public void ExportMultiReport(int thangDauTien, int namDauTien, int thangCuoi, int namCuoi,String maBCTruoc,String path, String description){
     Date todayD=new Date(System.currentTimeMillis()); 

//Khai bao dinh dang ngay thang
            SimpleDateFormat dayFormat= new SimpleDateFormat("dd/MM/yyyy"); 

//parse ngay thang sang dinh dang va chuyen thanh string.
             String todayS=dayFormat.format(todayD.getTime()); 
      
       while(namDauTien <= namCuoi){
            if(namDauTien<namCuoi){
                    while(thangDauTien <=12 && namDauTien <namCuoi){
                       if(thangDauTien<12){
                         
                             exportStudentMarkToPdf(thangDauTien,namDauTien, LayMaBCTTheoThangNam(thangDauTien, namDauTien),maBCTruoc,todayS,path+"\\BAOCAOTON_T"+thangDauTien+"_N"+namDauTien, description,false);
                               thangDauTien++;
                             maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                       }else if(thangDauTien ==12){
                         
                              exportStudentMarkToPdf(thangDauTien,namDauTien,  LayMaBCTTheoThangNam(thangDauTien, namDauTien),maBCTruoc,todayS,path+"\\BAOCAOTON_T"+thangDauTien+"_N"+namDauTien, description,false);
                                  namDauTien++;
                             thangDauTien=1; 
                              maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                       }
                    }
            }
            else if(namDauTien == namCuoi){
                while(thangDauTien<=thangCuoi){
                    if(thangDauTien<12){
                        
                        if(thangDauTien == thangCuoi){
                            exportStudentMarkToPdf(thangDauTien,namDauTien, LayMaBCTTheoThangNam(thangDauTien, namDauTien),maBCTruoc,todayS,path+"\\BAOCAOTON_T"+thangDauTien+"_N"+namDauTien, description,true);
                        }
                        else
                              exportStudentMarkToPdf(thangDauTien,namDauTien, LayMaBCTTheoThangNam(thangDauTien, namDauTien),maBCTruoc,todayS,path+"\\BAOCAOTON_T"+thangDauTien+"_N"+namDauTien,  description,false);
                        thangDauTien++;
                        maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                    }
                }
                namDauTien++;
            }
        }
 }
 public boolean checkPreviousReport(JIFBaoCaoTon  message){
     
      int thangChon = Integer.parseInt(cb_Thang.getSelectedItem().toString());
     int namChon  =Integer.parseInt(cb_Nam.getSelectedItem().toString());
     String maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
     ResultSet res = new BUS.BaoCaoTon().LayThangBCT(maBCTruoc);
    
     int thangBC = 0,namBC = 0,thangBCDauTien = 0, namBCDauTien = 0;
        try {
            while(res.next()){
                thangBC = Integer.parseInt(res.getString(1));
                namBC = Integer.parseInt(res.getString(2));}
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        ResultSet res2 = new BUS.BaoCaoTon().LayThangBCT("BCT001");
        try {
             while(res2.next()){
            thangBCDauTien = Integer.parseInt(res2.getString(1));
              namBCDauTien = Integer.parseInt(res2.getString(2));
             }
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
      
      //Kiểm tra xem có dữ liệu hay không
     Date todayD=new Date(System.currentTimeMillis()); 
     if(namChon > (todayD.getYear()+1900)){
              message.message = "Báo cáo không thể lập vì thời gian lập vượt thời gian hiện tại";
              return false;
     }
     if(namChon ==(todayD.getYear()+1900) && thangChon > (todayD.getMonth()+1)){
              message.message = "Báo cáo không thể lập vì thời gian lập vượt thời gian hiện tại";
              return false;
     }
     if(namChon<namBCDauTien){
          message.message = "Không thể lập báo cáo vì dữ liệu không tồn tại";
         return false;
     }
      if(namChon == namBCDauTien){
         if(thangChon<thangBCDauTien){
              message.message  = "Không thể lập báo cáo vì dữ liệu không tồn tại";
               return false;
         }
     }
     if(namBC == namChon){
                if(thangBC +1< thangChon){
                   message.message  ="Không thể lập báo cáo tháng "+ thangChon+ " vì chưa lập báo cáo tháng "+(thangChon-1)+" năm "+namChon+".Hãy thử tùy chọn Lập Báo Cáo Tự Động trước!";
                    return false;
                }
     } else if(namBC < namChon)
     {
            if(namBC+1 == namChon){
                if(thangBC<12){
                 if(thangChon!=1)
                        message.message ="Không thể lập báo cáo tháng "+ thangChon+ " vì chưa lập báo cáo tháng "+(thangChon-1)+ " năm "+namChon+".Hãy thử tùy chọn Lập Báo Cáo Tự Động trước!";
                 else 
                      message.message ="Không thể lập báo cáo tháng "+ thangChon+ " vì chưa lập báo cáo tháng "+12+ " năm "+(namChon-1)+".Hãy thử tùy chọn Lập Báo Cáo Tự Động trước!";
                    return false;
                } else if(thangBC ==12){
                    if(thangChon!=1){
                        message.message ="Không thể lập báo cáo tháng "+ thangChon+ " vì chưa lập báo cáo tháng "+(thangChon-1)+ " năm "+namChon+".Hãy thử tùy chọn Lập Báo Cáo Tự Động trước!";
                         return false;
                    }
                }
                
            }
            else if(namBC+1<namChon){
                 message.message ="Không thể lập báo cáo tháng "+ thangChon+ " vì chưa lập báo cáo tháng "+(thangChon-1)+ " năm "+namChon+".Hãy thử tùy chọn Lập Báo Cáo Tự Động trước!";
                 return false;
            }
     }
     
     return true;
 }
 
 public String getPreviousId(String id){
            if("BCT001".equals(id.trim()))
                return "BCT001";
            String temp =id.substring(3, id.length()).trim();
             int order;
            order = Integer.valueOf(temp) - Integer.valueOf(1);
            if(order<10){
                return "BCT00"+String.valueOf(order);
            }
            else if(order>=10 && order <100){
                return "BCT0"+String.valueOf(order);
            }else if(order>=100){
                return "BCT"+String.valueOf(order);
            }
        return null;
 }
 public void TaoBaoCaoTuDong(){
     int thangChon = Integer.parseInt(cb_Thang.getSelectedItem().toString());
     int namChon  =Integer.parseInt(cb_Nam.getSelectedItem().toString());
     String maBCTruoc =getPreviousId(new BUS.BaoCaoTon().GenerateID());
     ResultSet res = new BUS.BaoCaoTon().LayThangBCT(maBCTruoc);
     int thangBC = 0,namBC = 0;
        try {
            while(res.next()){
                thangBC = Integer.parseInt(res.getString(1));
                namBC = Integer.parseInt(res.getString(2));
            }
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
        
       while(namBC <= namChon){
            if(namBC<namChon){
                    while(thangBC <=12 && namBC <namChon){
                       if(thangBC<12){
                            thangBC++;
                            Insert(String.valueOf(thangBC),String.valueOf(namBC),maBCTruoc);
                            maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                       }else if(thangBC ==12){
                             namBC++;
                             thangBC=1;
                             Insert(String.valueOf(thangBC),String.valueOf(namBC),maBCTruoc);
                               maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                       }
                    }
            }
            else if(namBC == namChon){
                while(thangBC<thangChon){
                    if(thangBC<12){
                        thangBC++;
                        Insert(String.valueOf(thangBC),String.valueOf(namBC),maBCTruoc);
                         maBCTruoc = getPreviousId(new BUS.BaoCaoTon().GenerateID());
                    }
                }
                namBC++;
            }
        }
        LoadData();
        btn_lapbaocaotudong.setEnabled(false);
 }
 
 private boolean Insert(String thang,String nam,String maBCTruoc)
    {
        try {
        new DTO.BaoCaoTon(new BUS.BaoCaoTon().GenerateID(),thang, nam).Insert();
        ResultSet  res = new BUS.BaoCaoTon().ThongKeTon( Integer.parseInt(thang),  Integer.parseInt(nam),maBCTruoc);
        while(res.next()){
                      new DTO.ChiTietBaoCaoTon(new BUS.ChiTietBaoCaoTon().GenerateID(),getPreviousId(new BUS.BaoCaoTon().GenerateID()),res.getString(2),res.getString(5),res.getString(6),res.getString(7)).Insert();
            }
        
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        
        return true;
    }
     
    public String LayMaBCTTheoThangNam(int thang, int nam){
         String maBC = null;
         try {
         ResultSet resMaBC = new BUS.BaoCaoTon().LayMaBCTTheoThangNam(thang, nam);
            while(resMaBC.next()){
                     maBC = resMaBC.getString(1);
            }
        } catch (SQLException ex) {
            Logger.getLogger(JIFBaoCaoTon.class.getName()).log(Level.SEVERE, null, ex);
        }
       return maBC;
    }
    public void LuuDuLieu(){
                if(thang_HienTai == null || nam_HienTai ==null || maBCTruoc_HienTai ==null)
                    return;
                JOptionPane j = null;
                int clickvalue =  j.showConfirmDialog(this, "Bạn có muốn lưu báo cáo tháng "+thang_HienTai+" năm "+nam_HienTai+"  xuống CSDL?","Xác Nhận",JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    //            if( j.getOptionType()==JOptionPane.OK_OPTION)
                if( clickvalue==JOptionPane.OK_OPTION)
                {
                    Insert(thang_HienTai, nam_HienTai, maBCTruoc_HienTai);
                    thang_HienTai = nam_HienTai = maBCTruoc_HienTai =null;
                }
            
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Luu;
    private javax.swing.JButton btn_XuatTatCaBaoCao;
    private javax.swing.JButton btn_lapbaocaotudong;
    private javax.swing.JButton btn_xuatBCTuyChon;
    private javax.swing.JComboBox cb_DenNam;
    private javax.swing.JComboBox cb_DenThang;
    private javax.swing.JComboBox cb_Nam;
    private javax.swing.JComboBox cb_Thang;
    private javax.swing.JComboBox cb_TuNam;
    private javax.swing.JComboBox cb_TuThang;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelTieuDe;
    private javax.swing.JMenuItem jMenuItemAdd;
    private javax.swing.JMenuItem jMenuItemDel;
    private javax.swing.JMenuItem jMenuItemLoad;
    private javax.swing.JMenuItem jMenuItemNhap;
    private javax.swing.JMenuItem jMenuItemPrint;
    private javax.swing.JMenuItem jMenuItemSua;
    private javax.swing.JMenuItem jMenuItemTim;
    private javax.swing.JMenuItem jMenuItemXuat;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JTable jTableTon;
    // End of variables declaration//GEN-END:variables
}
